﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;

namespace Willson.JsbManager.Dal
{
    class AppConfig
    {

        /// <summary>
        /// 获取连接字符串
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                SqlConnectionStringBuilder connbuild = new SqlConnectionStringBuilder();

                connbuild.DataSource = GetAppConfig("DataSource");
                connbuild.InitialCatalog = GetAppConfig("InitialCatalog");
                connbuild.UserID = "sa";
                connbuild.Password = GetAppConfig("PassWord");
                connbuild.ConnectTimeout = Convert.ToInt32(GetAppConfig("ConnectTimeout"));
                


                return connbuild.ConnectionString;
            }
        }

        /// <summary>
        /// 根据给定的项目名称得到该项目的值
        /// </summary>
        /// <param name="strKey">要查找的项目名称</param>
        /// <returns>项目值</returns>
        private static string GetAppConfig(string strKey)
        {
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == strKey)
                {
                    return ConfigurationManager.AppSettings[strKey];
                }
            }

            return "none";
        }

        ///// <summary>
        ///// 更新项目内容
        ///// </summary>
        ///// <param name="newKey">要更新的项目名称</param>
        ///// <param name="newValue">要更新的项目的内容</param>
        //private static void UpdateAppConfig(string newKey, string newValue)
        //{
        //    bool isModified = false;
        //    foreach (string key in ConfigurationManager.AppSettings)
        //    {
        //        if (key == newKey)
        //        {
        //            isModified = true;
        //        }
        //    }

        //    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        //    if (isModified)
        //    {
        //        config.AppSettings.Settings.Remove(newKey);
        //    }

        //    config.AppSettings.Settings.Add(newKey, newValue);
        //    config.Save(ConfigurationSaveMode.Modified);

        //    ConfigurationManager.RefreshSection("appSettings");
        //}

        private AppConfig()
        {
        }
    }
}
